package com.laikan.reader.bookfriend.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.laikan.library.components.fragments.BasicFragment;
import com.laikan.library.managers.ToastMgr;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.adapter.BaseListAdapter;
import com.laikan.reader.bookfriend.base.IView;
import com.laikan.reader.bookfriend.view.DividerItemDecoration;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.TipInfoLayout;
import com.socks.library.KLog;

import java.util.List;

/**
 * Created by lingyt on 2016/11/15.
 * 带加载更多的ListFragment
 */
public abstract class BaseListFragment extends BasicFragment implements IView {
    protected RecyclerView mRecyclerView;
    protected ProgressBar_Modern mProgressBar;
    protected TipInfoLayout mTipinfoLayout;
    protected TextView mTvEmptyTip;
    protected BaseListAdapter mAdapter;
    protected Activity mActivity;

    protected static final int STATE_LOADING = 1;
    protected static final int STATE_ERROR = 2;
    protected static final int STATE_EMPTY = 3;
    protected static final int STATE_SUCCESS = 4;
    protected static final int STATE_NONE = -1;
    protected int mState = STATE_NONE;

    protected int currPage = 1;
    protected String args = "测试";
    protected boolean hasMore;
    protected boolean isLoadOnce;
    protected Bundle mBundle;
    protected Gson mGson;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle = getArguments();
        mGson = new Gson();
        if (mBundle != null) {
            args = mBundle.getString("KEY","");
           KLog.w(args,"onCreate log key获取成功 args ="+args);
        }
    }

    protected int getLayoutId() {
        return R.layout.fragment_list_defalult;
    }

    @Override
    protected void assignViews() {
        LayoutInflater.from(getActivity()).inflate(getLayoutId(), mBodyView);
        mTipinfoLayout = (TipInfoLayout) mBodyView.findViewById(R.id.tipinfo);
        mProgressBar = (ProgressBar_Modern) mBodyView.findViewById(R.id.progressBar);
        mTvEmptyTip = (TextView) mBodyView.findViewById(R.id.item_tv_empty);
        initListViewAndAdapter();

    }

    public void initListViewAndAdapter() {
        mRecyclerView = (RecyclerView) mBodyView.findViewById(R.id.recyclerview);

        if (mAdapter == null) {
            mAdapter = getAdapter();
            mRecyclerView.setAdapter(mAdapter);

            mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        } else {
            mAdapter.notifyDataSetChanged();
        }

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (hasMore && isSlideToBottom(mRecyclerView)) {//避免重复加载更多数据
                   KLog.w(args,"hasMore = "+hasMore+"  有更多数据，发起加载更多请求");
                    sendLoadMoreRequest();
                }else{
                   KLog.w(args,"onScrolled 没有更多数据");
                }
            }
        });
    }

    @Override
    protected void initData() {
       KLog.w(args,"initData，初始化页面数据....");
        sendRequestData();
    }

    @Override
    protected abstract void setListener();


    protected abstract BaseListAdapter getAdapter();


    protected void sendRequestData() {

        mState = STATE_LOADING;
       KLog.w(args,"刷新页面数据，当前页为1页，发起数据请求....");
        loadData(1);//从第一页开始加载数据
    }

    protected void sendLoadMoreRequest() {
        mState = STATE_LOADING;
       KLog.w(args,"加载更多数据，加载第 "+currPage+" 页数据。。");
        loadData(currPage);
    }

    protected abstract void loadData(int pageNo);


    protected void showData(List list) {
        switch (mState) {
            case STATE_SUCCESS:
                onRequestDataSuccess(list);
                break;
            case STATE_EMPTY:
                onRequestDataEmpty();
                break;
            case STATE_ERROR:
                onRequestDataError();
                break;
            default:
                break;
        }
    }

    protected int checkData(Object obj) {
        if (obj == null) {
           KLog.w(args,"data = null,服务器返回数据出错");
            return STATE_ERROR;
        } else if (obj instanceof List) {
            List list = (List) obj;
            if (list.size() == 0) {
               KLog.w(args,"data size = 0,服务器返回数据为空");
                return STATE_EMPTY;
            }

            if (list.size() < 10) {//根据数据的长度判断，让footer显示或隐藏
                changeAdapterState(false);
                hasMore = false;
            } else {
                hasMore = true;
                changeAdapterState(true);
            }
            currPage++;//数据加载成功页码+1
           KLog.w(args,"check data 数据长度为：" + list.size());
        }

        return STATE_SUCCESS;
    }

    public void changeAdapterState(boolean hasMore){
        mAdapter.setHasMoreState(hasMore);
    }

    protected void onRequestDataError() {
        if (!isLoadOnce) {
           KLog.w(args,"服务器返回数据出错，且为第一次加载数据，显示错误页面提示");
            mTipinfoLayout.setLoadError(R.string.laikan_network_anomaly);
            mTipinfoLayout.setOnClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendRequestData();
                }
            });
        } else {
            ToastMgr.showShortToast("网络异常，请检查网络");
           KLog.w(args,"服务器返回数据出错");
        }
    }

    protected void onRequestDataEmpty() {
       KLog.w(args,"isLoadOnce = "+isLoadOnce+"----"+"onRequestDataEmpty");
        if (!isLoadOnce) {
           KLog.w(args,"服务器返回数据为空，且为第一次加载数据，显示空页面提示");
            mTipinfoLayout.setEmptyData(R.string.test, R.drawable.book_list_null);
        } else {
            ToastMgr.showShortToast("服务器返回数据为空");
           KLog.w(args,"服务器返回数据为空");
        }
    }

    protected void onRequestDataSuccess(List list) {
       KLog.w(args,"数据请求成功，开始刷新页面数据....");
        isLoadOnce = true;
        mAdapter.addData(list);
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public void showProgress() {
       KLog.w(args,"显示进度条---isLoadOnce = "+isLoadOnce);
        if (!isLoadOnce) {
            mTipinfoLayout.setLoading();
        } else {
            mProgressBar.setShow();
        }
    }

    @Override
    public void hideProgress() {
       KLog.w(args,"隐藏进度条---isLoadOnce = "+isLoadOnce);
        if (!isLoadOnce && (mState == STATE_EMPTY || mState == STATE_ERROR)){
            //如果是第一次加载数据，设置数据的时候已经做了处理，不需要再做处理
            return;
        }
        mTipinfoLayout.setHide();
        mProgressBar.setHide();
    }

    /**
     * 判断RecycleView是否滑动到底部
     *
     * @param recyclerView
     * @return
     */
    public boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }

    private  Object obj;
    public void setFragmentData(Object obj) {
        this.obj = obj;
       KLog.w(args,"设置fragment数据 data ==null ?"+(obj == null));
        refreshFragmentData();
    }

    public abstract void refreshFragmentData();

    public  Object getFragmentData(){
        return obj;
    }
}
